package station;

/**
 * Vorlesung: Verteilte Systeme
 * Aufgabe  : 04
 * 
 * @author Benjamin Burchard
 * @author Tell Mueller-Pettenpohl
 * 
 */

import static station.DataMessage.DATA_LENGTH;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

import timeDivisionMultipleAccess.TimeSyncer;

public class Sender implements Runnable {

	private MulticastSocket mcastSocket;
	private String mcastAddr;
	private int mcastPort;
	private byte actFreeSlot;
	private byte udpBuffer[] = new byte[DATA_LENGTH];
	private TimeSyncer syncer;

	/**
	 * Creates a new Sender
	 * 
	 * @param mcastAddr
	 * @param mcastPort
	 * @param actFreeSlot
	 * @param dataBuffer
	 * @param syncer
	 */
	public Sender(String mcastAddr, int mcastPort, byte actFreeSlot,
			byte[] dataBuffer, TimeSyncer syncer) {
		// Multicast
		try {
			this.mcastSocket = new MulticastSocket();
		} catch (IOException e) {
			e.printStackTrace();
		}
		this.mcastAddr = mcastAddr;
		this.mcastPort = mcastPort;
		 // UDP
		this.udpBuffer = dataBuffer;
		this.actFreeSlot = actFreeSlot;
		this.syncer = syncer;
	}

	/**
	 * Get the udpBuffer
	 * 
	 * @return the udpBuffer
	 */
	// TODO: Wozu gibts das? - Benny
	public byte[] getBuffer() {
		return udpBuffer;
	}

	// TODO Problem: every new Sender object has a new TimeSyncer... sync
	// problem? -refs by constructor
	private void send(byte[] newBuffer) throws IOException {
		System.out.println("Sender send: " + newBuffer);
		mcastSocket.send(new DatagramPacket(newBuffer, newBuffer.length,
				InetAddress.getByName(mcastAddr), mcastPort));
	}

	public void run() {
		System.out.println("Sender STARTED!");
		DatagramPacket packet = new DatagramPacket(udpBuffer, udpBuffer.length);
		try {
			send(DataMessage.packMessage(packet.getData(), actFreeSlot,
					syncer.syncDispatchTime(syncer.getCurrentTime())));
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		mcastSocket.close();
		System.out.println("Sender FINISHED!");
	}
}
